package com.lsq.tucao.express.controller;

import com.lsq.tucao.express.bean.po.Picture;
import com.lsq.tucao.express.response.JsonResult;
import com.lsq.tucao.express.service.PictureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Autowired
    private PictureService pictureService;

    /**
     * @author lsq
     * @description 上传图片
     * @param pictureId 图片Id
     * @param pictureFile 图片文件
     * @return com.lsq.tucao.express.response.JsonResult
     * @create 2021/4/21 19:05
     */
    @PutMapping
    public JsonResult postPicture(@RequestParam Long pictureId,
                                  @RequestParam String title,
                                  @RequestParam String content,
                                  @RequestParam(required = false) MultipartFile pictureFile){
        try {
            return pictureService.postPicture(pictureId,title,content,pictureFile);
        } catch (Exception e) {
            log.error("上传图片时发生异常",e);
            return new JsonResult(500,"上传图片时发生异常");
        }
    }

    /**
     * @author lsq
     * @description 通过id获取图片
     * @param id
     * @param response
     * @return void
     * @create 2021/4/21 20:13
     */
    @GetMapping("/one")
    public void getPictureById(@RequestParam Long id, HttpServletResponse response){
        OutputStream outputSream = null;
        InputStream in = null;
        try {
            Picture picture = pictureService.getPictureById(id);
            if(picture != null){
                byte[] data = picture.getPicture();
                response.setContentType("image/jpg");
                response.setCharacterEncoding("UTF-8");
                outputSream = response.getOutputStream();
                in = new ByteArrayInputStream(data);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf, 0, 1024)) != -1) {
                    outputSream.write(buf, 0, len);
                }
            }else {
                log.error("获取图片失败");
            }
        } catch (IOException e) {
            log.error("获取图片时出现异常",e);
        } finally {
            try {
                if(outputSream != null){
                    outputSream.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (Exception e) {
                log.error("关闭流时出现异常",e);
            }
        }
    }


    @GetMapping("/all")
    public JsonResult getAllPicture(){
        return pictureService.getAllPicture();
    }

}
